import React, {JSX, useState} from "react";
import Taro from "@tarojs/taro";
import {Form, Image, Input, Text, View} from "@tarojs/components";
import './index.scss'
import '../f_pre/index.scss'
import {EFoodOrderItemType, FoodOrderItem, IFoodCateItem} from "../com/FoodItem";
import {decodeURIByRouteParams, modelToast} from "../../../utils";
import '../../../reset.scss'
import {getStoreSaveList} from "../../../utils/storage";
import {SubmitFood} from "../../../api/bus/food";

// mock 数据
const model = {
  Name: '',
  Tel: '18757574295',
  note: '',
  Orders: getStoreSaveList(),
  Rooms: (new Date().getTime() * Math.random()).toString().slice(10),
  DeliveryTime: new Date(),
  Address: '',
  Way: 0, // 0 是堂食， 1是外送
}

export const SubmitPage: React.FC = (): JSX.Element => {
  const saveList: Array<IFoodCateItem> = getStoreSaveList();
  const [AddressRenderStyle, setAddressRenderStyle] = useState({display: 'none'});
  const [formModel, setFormModel] = useState(model);
  console.log('加载')
  const onSetFormModel = (target) => {
    const newT = {...formModel, ...target};
    setFormModel(newT);
  }

  const onSubmitFood = () => {
    SubmitFood(formModel).then(_ => {
      return Taro.redirectTo({url: 'subPages/food/f_order/index'})
    })
  }

  const onFormSubmit = e => {
    e.preventDefault();
    try {
      validateForm();
      console.log(formModel, '提交的数据');
      onSubmitFood();
    } catch (err) {
      console.log('错误')
      return modelToast({title: err.message})
    }
  }
  const validateForm = () => {
    if (!formModel.Name || formModel.Name.trim() === '') {
      throw new Error('请输入联系人')
    }

    if (!formModel.Rooms || formModel.Rooms.trim() === '') {
      throw new Error('请输入房间号')
    }

    if (!formModel.Tel || formModel.Tel.trim() === '') {
      throw new Error('请输入联系电话')
    } else if (!/^\d{11}$/.test(formModel.Tel.trim())) {
      throw new Error('请输入有效联系电话')
    }
  }

  const ways: Array<IWays> = [
    {
      text: '堂食',
      icon: require('@/static/images/food/f_pre/Way-tang_shi.png'),
      Way: EWay.堂食,
    },
    {
      text: '外送',
      icon: require('@/static/images/food/f_pre/Way-wai_song.png'),
      Way: EWay.外送,
    },
  ]

  const onWay = (item: IWays) => {
    onSetFormModel({Way: item.Way});
    const display: string = item.Way === 0 ? 'none' : 'block';
    setAddressRenderStyle({display})
  }

  return (
    <View className='SubmitPage'>
      <View className='top'>
        <View className='title align-center'>
          <Image className='location' src={require('@/static/images/food/f_pre/location.png')}></Image>
          <View className='text'>{decodeURIByRouteParams('HotelName')}</View>
        </View>

        <View className='ways justify-between'>
          {ways.map(item => (
            <View
              className={`item flex-center ${item.Way === formModel.Way ? 'active' : ''}`}
              onClick={() => onWay(item)} key={item.text}
            >
              <Image className='icon' src={item.icon}></Image>
              <Text className='text'>{item.text}</Text>
              <Image
                style={{display: item.Way === formModel.Way ? 'block' : 'none'}}
                className='selected'
                src={require('@/static/images/food/f_pre/Way-selected.png')}></Image>
            </View>
          ))}
        </View>
      </View>
      <View className='form'>
        <Form>
          <View className='align-center justify-between form-item'>
            <Text>联系人</Text>
            <Input
              type='text'
              placeholder='请输入联系人'
              maxlength={20}
              value={formModel.Name}
              onInput={(e) => onSetFormModel({Name: e.detail.value})}
            />
          </View>

          <View className='align-center justify-between form-item'>
            <Text>房间号</Text>
            <Input
              type='text'
              placeholder='请输入房间号'
              maxlength={10}
              value={formModel.Rooms}
              onInput={(e) => onSetFormModel({Rooms: e.detail.value})}
            />
          </View>

          <View className='align-center justify-between form-item'>
            <Text>联系电话</Text>
            <Input
              type='text'
              placeholder='请输入联系电话'
              maxlength={20}
              value={formModel.Tel}
              onInput={(e) => onSetFormModel({Tel: e.detail.value})}
            />
          </View>

          <View style={AddressRenderStyle} className='form-item'>
            <View className='align-center justify-between form-item'>
              <Text>送达地址</Text>
              <Input
                type='text'
                placeholder='请输入送达地址'
                maxlength={20}
                value={formModel.Address}
                onInput={(e) => onSetFormModel({Address: e.detail.value})}
              />
            </View>
            {/*<View className='align-center justify-between form-item'>*/}
            {/*  <Text>送达时间</Text>*/}
            {/*  <Input*/}
            {/*    type='text'*/}
            {/*    placeholder='请输入送达时间'*/}
            {/*    maxlength={20}*/}
            {/*    value={formModel.DeliveryTime}*/}
            {/*    onInput={(e) => onSetFormModel({DeliveryTime: e.detail.value})}*/}
            {/*  />*/}
            {/*</View>*/}
          </View>

        </Form>
      </View>
      <SaveList></SaveList>
      <View className='formNote'>
        <View className='align-center justify-between form-item'>
          <Text>备注</Text>
          <Input
            type='text'
            placeholder='请输入备注'
            maxlength={80}
            value={formModel.note}
            onInput={(e) => onSetFormModel({note: e.detail.value})}
          />
        </View>
      </View>
      <View className='formSubmit'>
        <View className='totalButton justify-between align-center'>
          <View className='left'>
            共计&nbsp;{saveList.length}&nbsp;件
          </View>
          <View className='right' onClick={onFormSubmit}>
            提交订单
          </View>
        </View>
      </View>
    </View>
  )
}

export const SaveList: React.FC = (): JSX.Element => {
  const saveList: Array<IFoodCateItem> = getStoreSaveList();
  return (
    <View className='SaveList'>
      <View className='title'>点餐信息</View>
      {saveList.map(item => (
        <FoodOrderItem
          key={item.Id}
          type={EFoodOrderItemType.readonly}
          item={item}
        ></FoodOrderItem>
      ))}
    </View>
  )
}

enum EWay {
  '堂食',
  '外送'
}

export interface IWays {
  icon: string,
  text: string,
  Way: EWay,
}

export default SubmitPage;
